package com.me.mygdxgame.renderer;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.me.mygdxgame.renderer.RenderObjects.BaseObject;

public class Context
{
	protected ShaderProgram shader;
	protected ArrayList<BaseObject> objs = new ArrayList<BaseObject>();
	protected boolean needZSort = false;
	protected SpriteBatch batch;
	
	static int count = 0;

	public Context(ShaderProgram shader)
	{
		this.shader = shader;
		ShaderProgram.pedantic = false;
	}

	public int getSize()
	{
		return objs.size();
	}

	public boolean addMesh(BaseObject obj)
	{

		boolean temp = objs.add(obj);
		if (temp == true)
		{
			needZSort = true;
			return true;
		}

		return false;
	}

	public boolean removeMesh(BaseObject obj)
	{
		return objs.remove(obj);
	}

	protected void zSort()
	{
		Collections.sort(objs, new Comparator<BaseObject>()
		{

			@Override
			public int compare(BaseObject A, BaseObject B)
			{
				if (A.getWorldPos().z < B.getWorldPos().z)
				{
					return 1;
				}
				else if (A.getWorldPos().z == B.getWorldPos().z)
				{
					return 0;
				}
				else
				{
					return -1;
				}
			}

		});

		needZSort = false;
	}

	public void Create()
	{

	}

	public void renderContext()
	{
		
		count++;
		
		if(count > 100)
		{
			Gdx.app.log("RenderContext", "Object Count: " + objs.size());
			count = 0;
		}
		
		GL20 gl = Gdx.graphics.getGL20();

		gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());

		gl.glEnable(GL20.GL_TEXTURE_2D);
		gl.glActiveTexture(GL20.GL_TEXTURE0);

		for (int i = 0; i < objs.size(); i++)
		{
			shader.begin();
			objs.get(i).getTexture().bind();
			shader.setUniformi("u_texture", 0);
			shader.setUniformMatrix("u_MVPMatrix", Camera.getInstance().getCamera().combined);
			shader.setUniformMatrix("u_mvMatrix", objs.get(i).getModelMatrix());
			objs.get(i).getMesh().render(shader, GL20.GL_TRIANGLES);
			shader.end();
		}

		gl.glDisable(GL20.GL_TEXTURE_2D);
	}

}
